package com.example.controller;

import com.example.common.Result;
import com.example.entity.Booking;
import com.example.entity.Room;
import com.example.service.BookingService;
import com.example.service.RoomAllocationService;
import jakarta.annotation.Resource;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/roomAllocation")
public class RoomAllocationController {

    @Resource
    private RoomAllocationService roomAllocationService;
    
    @Resource
    private BookingService bookingService;
    
    /**
     * 为预订分配房间
     */
    @PostMapping("/allocate")
    public Result allocateRoom(@RequestBody Booking booking) {
        Room allocatedRoom = roomAllocationService.allocateRoom(booking);
        
        Map<String, Object> data = new HashMap<>();
        data.put("booking", booking);
        data.put("allocatedRoom", allocatedRoom);
        
        return Result.success(data);
    }
    
    /**
     * 获取可用房间列表
     */
    @GetMapping("/availableRooms")
    public Result getAvailableRooms(
            @RequestParam Long hotelId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate checkInDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate checkOutDate) {
        
        // 检查参数
        if (checkInDate.isAfter(checkOutDate)) {
            return Result.error("400", "入住日期不能晚于退房日期");
        }
        
        List<Room> availableRooms = roomAllocationService.getAvailableRooms(hotelId, checkInDate, checkOutDate);
        return Result.success(availableRooms);
    }
    
    /**
     * 为已有预订更新房间分配
     */
    @PutMapping("/update/{bookingId}")
    public Result updateRoomAllocation(
            @PathVariable Long bookingId,
            @RequestParam(required = false) Long newRoomId) {
        
        // 获取预订信息
        Booking booking = bookingService.selectById(bookingId);
        if (booking == null) {
            return Result.error("404", "预订不存在");
        }
        
        // 如果指定了新房间，更新预订的房间ID
        if (newRoomId != null) {
            booking.setRoomId(newRoomId);
        }
        
        // 重新分配房间
        Room allocatedRoom = roomAllocationService.allocateRoom(booking);
        
        // 更新预订信息
        bookingService.update(booking);
        
        Map<String, Object> data = new HashMap<>();
        data.put("booking", booking);
        data.put("allocatedRoom", allocatedRoom);
        
        return Result.success(data);
    }
} 